package com.dk.controller;

import com.dk.common.GlobalVariable;
import com.dk.exception.SimpleException;
import com.dk.util.HttpLogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileUrlResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 下载文件用
 *
 * @author: A11181121050450
 * @date: 2020-04-20 14:33
 */
@Slf4j
@Controller
public class DownloadFileController {
    /**
     * 下载文件
     * @param request
     * @return
     * @throws MalformedURLException
     */
    @GetMapping("downloadFile")
    public ResponseEntity<Resource> downloadFile(HttpServletRequest request) {
        HttpLogUtil.printHeader(request);
        if(StringUtils.isEmpty(GlobalVariable.downloadFilePath)){
            throw new SimpleException("请选择文件");
        }
        Path source = Paths.get(GlobalVariable.downloadFilePath);
        if(!source.toFile().exists()){
            throw new SimpleException("文件不存在，请检查路径");
        }
        Resource resource =null;
        try {
            // Load file as Resource
            resource = new FileUrlResource(GlobalVariable.downloadFilePath);
        }catch (MalformedURLException e) {
            throw new SimpleException("文件不存在，请检查路径",e);
        }

        // Try to determine file's content type
        String contentType = null;
        String fileName = "";
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
            fileName = resource.getFile().getName();
            fileName=new String(fileName.getBytes(),"iso8859-1");
        } catch (IOException ex) {
            log.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if(contentType == null) {
            contentType = "application/octet-stream";
        }
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .body(resource);
    }
}
